package zzu.xjc.http;

import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.regex.Pattern;


public class HttpFilterChain {
    private final ArrayList<FilterEntry> list = new ArrayList<>();

    void addFilter(String urlPattern,Http.Method method,HttpFilter filter){
        list.add(new FilterEntry(Pattern.compile("^" + urlPattern).asPredicate(),method,filter));
    }

    boolean doFilter(HttpRequest request,HttpResponse response){
        for (FilterEntry entry : list) {
            if (entry.predicate.test(request.url()) &&
                    ( entry.method.equals(Http.Method.ANY) || entry.method.equals(request.method()) )){
                if (!entry.filter.filter(request, response)){
                    return false;
                }
            }
        }
        return true;
    }

    private static class FilterEntry{
        Predicate<String> predicate;
        Http.Method method;
        HttpFilter filter;

        public FilterEntry(Predicate<String> predicate, Http.Method method, HttpFilter filter) {
            this.predicate = predicate;
            this.method = method;
            this.filter = filter;
        }
    }
}
